package com.mingtu.guards.activity;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.TileOverlay;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.ConvertLatlng;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.EquiSingleChoiceTextAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.InfraredBubbleInfoBean;
import com.mingtu.guards.bean.InfraredDequiBean;
import com.mingtu.guards.utils.MarkerOptionsUtils;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.view.CommonMapView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.guards.utils.MyConstant.INFO_WINDOW_OFF_SET_Y;

public class InfraredMapActivity extends MyBaseActivity implements AMap.OnMarkerClickListener,
        AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener, AMap.OnMapTouchListener {
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_list_mode)
    ImageView ivListMode;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_fold_depart)
    TextView tvFoldDepart;
    @BindView(R.id.layout_arrow_depart)
    LinearLayout layoutArrowDepart;
    @BindView(R.id.layout_depart)
    RelativeLayout layoutDepart;
    @BindView(R.id.recycler_depart)
    RecyclerView recyclerDepart;
    @BindView(R.id.tv_fold_equi)
    TextView tvFoldEqui;
    @BindView(R.id.layout_arrow_equi)
    LinearLayout layoutArrowEqui;
    @BindView(R.id.layout_equi)
    RelativeLayout layoutEqui;
    @BindView(R.id.recycler_equi)
    RecyclerView recyclerEqui;
    @BindView(R.id.tv_reset)
    TextView tvReset;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.layout_right_drawer)
    LinearLayout layoutRightDrawer;
    @BindView(R.id.layout_drawer)
    DrawerLayout layoutDrawer;
    @BindView(R.id.view_block)
    View viewBlock;
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private View infoWindow;
    private TileOverlay tileOverlay;
    private boolean isSwitch = true;
    private ImmersionBar immersionBar;
    private Marker clickMarker;
    private CommonMapView commonMapView;
    private String[] infraredArray = null; //此账号和markerList存在对应关系
    private List<String> infraredList = new ArrayList<>();
    private EquiSingleChoiceTextAdapter filteDepartAdapter;
    private List<InfraredDequiBean.DataBean.ListBean> dataBeans;
    private List<String> deptNameList = new ArrayList<>();
    private List<String> deptEquiList = new ArrayList<>();
    private EquiSingleChoiceTextAdapter filteEquiAdapter;
    private String equiName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_equi_map;
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();

        int statusBarHeight = BarUtils.getStatusBarHeight();//单位是px

        ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) viewBlock.getLayoutParams();
        layoutParams.height = statusBarHeight;
        viewBlock.setLayoutParams(layoutParams);
    }

    @Override
    protected void initData() {
        //部门列表
        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(this);
        flm1.setFlexWrap(FlexWrap.WRAP);
        flm1.setFlexDirection(FlexDirection.ROW);
        flm1.setAlignItems(AlignItems.STRETCH);
        flm1.setJustifyContent(JustifyContent.FLEX_START);
        recyclerDepart.setLayoutManager(flm1);

        filteDepartAdapter = new EquiSingleChoiceTextAdapter(BaseApplication.getBaseApplication(), null);
        recyclerDepart.setAdapter(filteDepartAdapter);
        filteDepartAdapter.setOnItemClickListener(new EquiSingleChoiceTextAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                filteDepartAdapter.upData(position);
                if (deptNameList != null && deptNameList.size() > 0) {
                    String currentDeptName = deptNameList.get(position);
                    List<String> equiList = getDeptEqui(currentDeptName);
                    filteEquiAdapter.upData(equiList);
                    equiName = null;
                }
            }
        });

        //设备列表
        FlexboxLayoutManager flm2 = new FlexboxLayoutManager(this);
        flm2.setFlexWrap(FlexWrap.WRAP);
        flm2.setFlexDirection(FlexDirection.ROW);
        flm2.setAlignItems(AlignItems.STRETCH);
        flm2.setJustifyContent(JustifyContent.FLEX_START);
        recyclerEqui.setLayoutManager(flm2);

        filteEquiAdapter = new EquiSingleChoiceTextAdapter(BaseApplication.getBaseApplication(), null);
        recyclerEqui.setAdapter(filteEquiAdapter);
        filteEquiAdapter.setOnItemClickListener(new EquiSingleChoiceTextAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                filteEquiAdapter.upData(position);
                if (deptEquiList.size() > 0) {
                    equiName = deptEquiList.get(position);
                }
            }
        });
    }

    @Override
    protected void getData() {

    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        commonMapView = findViewById(R.id.common_map_view);
        commonMapView.setMapParam(savedInstanceState);
        aMap = commonMapView.getAMap();
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapTouchListener(this);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                getDequiList();

            }
        });
        // 设置Marker跟随地图旋转
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                float angle = cameraPosition.bearing;

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {

            }
        });
        //自定义瓦片
        tileOverlay = commonMapView.getTileOverlay();
    }

    @OnClick({R.id.iv_switch, R.id.iv_back, R.id.iv_list_mode, R.id.tv_cancel, R.id.tv_sure, R.id.tv_reset})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    tileOverlay.setVisible(false);
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    tileOverlay.setVisible(true);
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
            case R.id.iv_list_mode:
                openRightDrawer();
                break;
            case R.id.tv_cancel:
                closeRightDrawers();
                break;
            case R.id.tv_reset:
                closeRightDrawers();
                filteDepartAdapter.resetData();
                filteEquiAdapter.resetData();
                filteEquiAdapter.upData(infraredList);
                equiName = null;
                break;
            case R.id.tv_sure:
                closeRightDrawers();
                if (equiName != null) {
                    //markerList 、infraredList 存储的数据是对应关系
                    if (infraredList.indexOf(equiName) != -1) {
                        int index = infraredList.indexOf(equiName);
                        clickMarker = markerList.get(index);
                        clickMarker.showInfoWindow();
                        aMap.animateCamera(CameraUpdateFactory.changeLatLng(clickMarker.getPosition()));
                        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                    }
                } else {
                    ToastUtils.showLong("请选择设备");
                }

                break;
        }
    }

    @Override
    protected void onDestroy() {

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        //自定义瓦片
        if (tileOverlay != null) {
            tileOverlay.setVisible(false);
            tileOverlay.remove();
        }

        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) ||
                    XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
                commonMapView.amapMoveCamera();
            } else {
                ToastUtils.showLong("定位权限获取失败");
            }
        }
    }

    /**
     * 设备信息
     */

    private void getDequiList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", 1);
        hashMap.put("pageSize", 500);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INF_DEQUI_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {

                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            InfraredDequiBean infraredDequiBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                infraredDequiBean = new InfraredDequiBean();
                                infraredDequiBean = gson.fromJson(result, InfraredDequiBean.class);
                                dataBeans = infraredDequiBean.getData().getList();
                                if (dataBeans != null) {
                                    int size = dataBeans.size();
                                    if (size > 0) {
                                        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
                                        ApplicationInfo appInfo = getApplicationInfo();
                                        for (int i = 1; i <= 24; i++) {
                                            int resID = getResources().getIdentifier("icon_infrared" + i, "mipmap", appInfo.packageName);
                                            giflist.add(BitmapDescriptorFactory.fromResource(resID));
                                        }

                                        deptNameList = dataBeans.stream().map(InfraredDequiBean.DataBean.ListBean::getDeptName).distinct().collect(Collectors.toList());
                                        if (deptNameList.size() > 0) {
                                            filteDepartAdapter.upData(deptNameList);
                                        }

                                        List<LatLng> latLngs = new ArrayList<>();
                                        //存储所有的设备名字，并在后面的检索逻辑中使用，此处逻辑很重要
                                        infraredList = new ArrayList<>();
                                        for (int i = 0; i < size; i++) {
                                            InfraredDequiBean.DataBean.ListBean listBean = dataBeans.get(i);
                                            String latitude = listBean.getLatitude();
                                            String longitude = listBean.getLongitude();
                                            if (!StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(longitude)) {
                                                String cameraName = listBean.getCameraName();
                                                String cameraCode = listBean.getCameraCode();
                                                String updateTime = listBean.getUpdateTime();

                                                int status = listBean.getStatus();
                                                int picCount = listBean.getPicCount();
                                                int batteryLevel = listBean.getBatteryLevel();

                                                double lat = Double.parseDouble(latitude);
                                                double lng = Double.parseDouble(longitude);
                                                String myLng = ConvertLatlng.getInstance().convertToSexagesimal(lng);
                                                String myLat = ConvertLatlng.getInstance().convertToSexagesimal(lat);

                                                HashMap<String, Object> myHashMap = new HashMap<>();
                                                myHashMap.put("cameraName", cameraName);
                                                myHashMap.put("cameraCode", cameraCode);
                                                myHashMap.put("updateTime", updateTime);
                                                myHashMap.put("batteryLevel", batteryLevel);
                                                myHashMap.put("status", status);
                                                myHashMap.put("picCount", picCount + "");
                                                myHashMap.put("location", myLat + "," + myLng);
                                                myHashMap.put("lat", lat + "");
                                                myHashMap.put("lng", lng + "");
                                                String infraredInfo = GsonUtils.toJson(myHashMap);
                                                LatLng location = new LatLng(lat, lng);
                                                latLngs.add(location);
                                                //添加Marker
                                                if (status == 1) {
                                                    Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions2(location, infraredInfo, INFO_WINDOW_OFF_SET_Y, giflist));
                                                    markerList.add(marker);


                                                } else if (status == 2) {
                                                    Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions1(location, infraredInfo, INFO_WINDOW_OFF_SET_Y, R.mipmap.icon_infrared_offline));
                                                    markerList.add(marker);
                                                }
                                                if (!StringUtils.isEmpty(cameraName)) {
                                                    infraredList.add(cameraName);
                                                } else {
                                                    infraredList.add(myLat + "," + myLng);
                                                }
                                            }
                                        }
                                        deptEquiList = infraredList;
                                        //展示全部设备
                                        filteEquiAdapter.upData(infraredList);

                                        if (latLngs.size() > 0) {
                                            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs), 200));
                                        }
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(this).inflate(R.layout.infrared_bubble_view, null);
        }

        return render(marker, infoWindow);

    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
//        marker.hideInfoWindow();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        clickMarker = marker;
        return false;
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (clickMarker != null) {
            boolean b = clickMarker.isInfoWindowShown();
            if (b) {
                clickMarker.hideInfoWindow();
            }
        }
    }

    /**
     * 自定义infowinfow窗口
     */
    public View render(Marker marker, View view) {
        String infraredInfo = marker.getTitle();
        Gson gson = GsonFactory.getSingletonGson();
        InfraredBubbleInfoBean infraredBubbleInfoBean = new InfraredBubbleInfoBean();
        infraredBubbleInfoBean = gson.fromJson(infraredInfo, InfraredBubbleInfoBean.class);

        String cameraName = infraredBubbleInfoBean.getCameraName();
        String cameraCode = infraredBubbleInfoBean.getCameraCode();
        String updateTime = infraredBubbleInfoBean.getUpdateTime();
        int batteryLevel = infraredBubbleInfoBean.getBatteryLevel();
        int status = infraredBubbleInfoBean.getStatus();
        String picCount = infraredBubbleInfoBean.getPicCount();
        String location = infraredBubbleInfoBean.getLocation();
        String latStr = infraredBubbleInfoBean.getLat();
        String lngStr = infraredBubbleInfoBean.getLng();

        LinearLayout layoutMarker = (LinearLayout) view.findViewById(R.id.layout);
        layoutMarker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //防止点击事件和touch事件冲突，所以采用此种方式跳转
                if (!StringUtils.isEmpty(cameraName)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("cameraName", cameraName);
                    IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), InfraredRecordPictureActivity.class, bundle);
                } else {
                    ToastUtils.showLong(getResources().getString(R.string.data_error));
                }

            }
        });
        LinearLayout layoutStatus = (LinearLayout) view.findViewById(R.id.layout_status);
        TextView tvName = (TextView) view.findViewById(R.id.tv_name);
        TextView tvCode = (TextView) view.findViewById(R.id.tv_code);
        TextView tvTime = (TextView) view.findViewById(R.id.tv_time);
        TextView tvElectric = (TextView) view.findViewById(R.id.tv_electric);
        TextView tvStatus = (TextView) view.findViewById(R.id.tv_status);
        TextView tvNum = (TextView) view.findViewById(R.id.tv_num);
        TextView tvLocation = (TextView) view.findViewById(R.id.tv_location);
        TextView tvNvi = (TextView) view.findViewById(R.id.tv_nvi);
        tvNvi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("lng", lngStr);
                bundle.putString("lat", latStr);
                bundle.putBoolean("isFire", false);
                IntentUtils.getInstance().readyGo(InfraredMapActivity.this, NaviMapActivity.class, bundle);

            }
        });

        if (!StringUtils.isEmpty(cameraName)) {
            tvName.setText(cameraName);
        }
        if (!StringUtils.isEmpty(cameraCode)) {
            tvCode.setText(cameraCode);
        }
        if (!StringUtils.isEmpty(updateTime)) {
            tvTime.setText(updateTime);
        }

        if (!StringUtils.isEmpty(picCount)) {
            tvNum.setText(picCount);
        }
        if (!StringUtils.isEmpty(location)) {
            tvLocation.setText(location);
        }
        tvElectric.setText(batteryLevel * 10 + "%");

        if (batteryLevel <= MyConstant.BATTERY_WARNIG_LEVEEL) {
            tvElectric.setTextColor(getResources().getColor(R.color.text_color_fec));
        } else {
            tvElectric.setTextColor(getResources().getColor(R.color.colorPrimary));
        }

        if (status == 1) {
            tvStatus.setText("在线");
            layoutStatus.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else if (status == 2) {
            tvStatus.setText("离线");
            layoutStatus.setBackgroundColor(getResources().getColor(R.color.bg_color_e45));
        }
        return view;
    }

    /**
     * 显示列表
     */
    public void showListPop() {
        if (infraredList != null && infraredList.size() >= 0) {
            infraredArray = new String[infraredList.size()];
            for (int i = 0; i < infraredList.size(); i++) {
                infraredArray[i] = infraredList.get(i);
            }

            new XPopup.Builder(this)
                    .hasShadowBg(true)
                    .maxHeight(ScreenUtils.getScreenHeight() / 2)
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .asCenterList("列表模式", infraredArray,
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    clickMarker = markerList.get(position);
                                    clickMarker.showInfoWindow();
                                    aMap.animateCamera(CameraUpdateFactory.changeLatLng(clickMarker.getPosition()));
                                    aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                                }
                            }).show();
        }

    }

    /**
     * 根据保护区名字查询设备
     *
     * @param currentDeptName
     * @return
     */
    private List<String> getDeptEqui(String currentDeptName) {
        deptEquiList = new ArrayList<>();
        if (dataBeans != null && dataBeans.size() > 0) {
            for (InfraredDequiBean.DataBean.ListBean listBean : this.dataBeans) {
                String deptName = listBean.getDeptName();
                if (currentDeptName.equals(deptName)) {
                    String cameraName = listBean.getCameraName();
                    deptEquiList.add(cameraName);
                }
            }
            return deptEquiList;
        } else {
            return deptEquiList;
        }
    }

    /**
     * 关闭右侧边栏
     */
    public void closeRightDrawers() {
        layoutDrawer.closeDrawer(layoutRightDrawer);
    }

    /**
     * 打开右侧边栏
     */
    public void openRightDrawer() {
        layoutDrawer.openDrawer(layoutRightDrawer);
    }

}